package com.leectrl.adapter;

import android.util.Log;

import com.leectrl.utils.Bus;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketHandler extends SimpleChannelInboundHandler<Object>{
    private   static ChannelGroup GlobalGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    public WebSocketHandler(){
        Bus.getInstance().on("zigbee_resp", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                String text=(String)message[0];
                TextWebSocketFrame tws = new TextWebSocketFrame(text);
                GlobalGroup.writeAndFlush(tws);
            }
        });
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        Log.e("SocketServer","socket 连接");
        GlobalGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        Log.e("SocketServer","socket 断开连接");
        GlobalGroup.remove(ctx.channel());
    }

}
